<template>
  <el-card>
    <div slot="header">
      <h3>临时项目商品-新增</h3>
    </div>
    <div class="project_goods_add">
      <el-form
        :model="formData"
        :disabled="!hasNoSubmitted"
        style="width: 80%"
      >
        <el-row type="flex" justify="space-between">
          <el-col :span="12">
            <el-form-item label="选择客户：" :required="true">
              <RemoteSelect
                placeholder="请选择客户"
                :optionKeys="['customerName', 'customerCode']"
                :echoValue="formData.customerCode"
                :echoOptions="[formData.customerName, formData.customerCode]"
                :remoteSelectOptions="remoteOptionsByCustomer"
                :handleClickButton="handleChooseCustomer"
                @getSelect="getCustomerInfoByRemote"
              />
            </el-form-item>
          </el-col>
          <el-form-item label="预计下架日期：" label-width="120px" :required="true">
            <el-date-picker
              v-model="formData.expectOffTime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-row>
        <el-form-item label="准入说明：" label-width="90px">
          <el-input
            type="textarea"
            resize="none"
            v-model.trim="formData.approvalDescription"
            show-word-limit
            placeholder="请输入准入说明"
            :autosize="{ minRows: 4 }"
          />
        </el-form-item>
      </el-form>
      <el-row>
        <skus-table
          ref="skusTable"
          showActionCol
          :tableHeight="480"
          :defaultMinWidth="100"
          :dataSource="tableInfo.list"
          :columns="tableInfo.columns"
          :loading="tableInfo.loading"
          :pageSizes="pageSizes"
          :pagination="pagination"
          :total="pagination.total"
          :showSelectCol="hasNoSubmitted"
          :selectionChange="handleSelectionChange"
          :actionRender="renderTableBtnAction"
          @pageChange="handlePageChange"
          @pageSizeSelect="handlePageSizeChange"
          @handleRowChange="handleInputNumberRowChange"
        >
          <div slot="content_context">
            <!-- 按钮操作栏 -->
            <BtnRender :render="renderBtnsBar" />
          </div>
        </skus-table>
      </el-row>
      <TableFooter v-if="!this.hasNoSubmitted" :data-source="operInfo" />
    </div>
    <!-- 选择客户弹框 -->
    <SelectCustomerDialog
      :visible.sync="dialogVisible.customer"
      @getSelectResults="getCustomerInfoByDialog"
    />
    <!-- 关联四级类弹框 -->
    <AssociatedDialog
      dialogTitle="关联四级类"
      currentType="1"
      :visible.sync="dialogVisible.category"
      @getSelectResults="getSelectCategory"
    />
    <!-- 关联品牌弹框 -->
    <AssociatedDialog
      dialogTitle="关联品牌"
      currentType="2"
      :visible.sync="dialogVisible.brand"
      @getSelectResults="getSelectBrand"
    />
    <!-- 关联计量单位弹框 -->
    <AssociatedDialog
      dialogTitle="关联计量单位"
      currentType="3"
      :visible.sync="dialogVisible.unit"
      @getSelectResults="getSelectUnit"
    />
  </el-card>
</template>
<script>
import SelectCustomerDialog from '../components/SelectCustomerDialog';
import RemoteSelect from '@/pages/commodity/components/RemoteSelect';
import BtnRender from '@/components/JSXRender/BtnRender';
import SkusTable from '@/components/skusTable';
import { getBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { TABLE_COLUMNS, VIEW_TABLE_COLUMNS, PITCURE_COL, ERROR_COL, CacheKey } from './constants/add';
import { PRODUCT_TYPES_ENUMS } from '@/constants/commodity';
import AssociatedDialog from '../components/AssociatedDialog';
import TableFooter from '../components/TableFooter';
import { generateUuid, createExcelByExport, removeSessionByRoute, toFixedCustomize } from '@/utils/bizUtils';
import {
  getOffMaxDaysService,
  exportTemplateService,
  submitTemporaryGoodsInfoService,
  querySubmittedInfoService,
  batchUpTemporaryGoodsService
} from '@/api/commodity/temporaryPurchasingGoods/temporaryProjectGoods';
import skusPage from '@/mixins/commodity/skusPage';
import selectCustomer from '../components/SelectCustomerDialog/mixins';
export default {
  mixins: [skusPage, selectCustomer],
  inject: ['reloadPage'],
  components: {
    SelectCustomerDialog,
    RemoteSelect,
    BtnRender,
    SkusTable,
    AssociatedDialog,
    TableFooter
  },
  data () {
    return {
      formData: {},
      // 表格信息
      tableInfo: {
        list: [],
        columns: [],
        selection: [],
        loading: false
      },
      pickerOptions: {},
      dialogVisible: {
        customer: false,
        category: false,
        brand: false,
        unit: false
      },
      btnLoading: {
        export: false,
        submit: false,
        batchUp: false
      },
      operInfo: {}
    }
  },
  mounted () {
    this.initAllData();
    this.echoSubmittedInfo();
  },
  beforeRouteLeave (to, from, next) {
    removeSessionByRoute({
      toName: to.name,
      notRemoveNames: 'imageTextManage',
      cacheKey: CacheKey
    });
    next();
  },
  computed: {
    hasNoSelection () {
      return this.tableInfo.selection.length === 0;
    },
    hasNoSubmitted () {
      const uuids = sessionStorage.getItem(CacheKey) ?? [];
      return uuids.length === 0;
    }
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const disabled = this.hasNoSelection;
      const importItem = {
        label: '导入数据',
        action: 'sysback/tempProjectSku/importTempProjectSku',
        methods: { handleUploadSuccess: this.handleImportData },
        isImport: true,
        loadingFn: state => { this.tableInfo.loading = state }
      }
      const firstStateBtns = [
        { label: '返回', method: this.handleGoBack },
        { label: '添加行', method: this.handleAddRow },
        { label: '关联品类', method: this.handleLinkCategory, disabled },
        { label: '关联品牌', method: this.handleLinkBrand, disabled },
        { label: '关联计量单位', method: this.handleLinkUnit, disabled },
        { label: '导出模板', method: this.handleExportTemplate, loading: this.btnLoading.export },
        importItem,
        { label: '提交', method: this.handleSubmit, loading: this.btnLoading.submit }
      ];
      const secondStageBtns = [
        { label: '保持下架状态', type: 'primary', method: this.handleKeepOffState },
        { label: '立即上架', type: 'primary', method: this.handleUpImmediately, loading: this.btnLoading.batchUp }
      ];
      const finalBar = this.hasNoSubmitted ? firstStateBtns : secondStageBtns;
      // 按钮通用属性填充
      const btnsBar = finalBar.map(item => ({ ...item, type: 'default', size: 'mini', hasAuth: false }));
      return getBtnsBar(h, btnsBar, this.showBtn);
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const deleteBtn = { label: '删除', method: this.handleDelete };
      const pictureBtn = { label: '图文', method: this.handleViewPicture };
      const actionList = [this.hasNoSubmitted ? deleteBtn : pictureBtn];
      return getTableAction({ h, row, actionList });
    },
    // 返回
    handleGoBack () {
      this.goToListPage();
    },
    // 添加行
    handleAddRow () {
      const newData = this.getNewRowData();
      this.tableInfo.list.push(newData);
    },
    // 关联品类
    handleLinkCategory () {
      this.dialogVisible.category = true;
    },
    // 关联品牌
    handleLinkBrand () {
      this.dialogVisible.brand = true;
    },
    // 关联计量单位
    handleLinkUnit () {
      this.dialogVisible.unit = true;
    },
    // 导出模板
    async handleExportTemplate () {
      const loadingFn = state => { this.btnLoading.export = state };
      const res = await exportTemplateService(loadingFn);
      createExcelByExport({ res, excelTitle: '临时项目商品新增' });
    },
    // 导入数据
    handleImportData (res) {
      this.tableInfo.list = res.retData.map(
        (item, index) => ({ ...item, frontUuid: generateUuid() + index })
      );
    },
    // 提交
    handleSubmit () {
      const isValidated = this.formData.customerCode && this.formData.expectOffTime;
      if (isValidated) this.submitAddInfo();
      else this.$message.warning('客户或预计下架日期不能为空');
    },
    // 表格勾选
    handleSelectionChange (list) {
      this.tableInfo.selection = list;
    },
    // 保持下架状态
    handleKeepOffState () {
      this.goToListPage();
    },
    // 立即上架
    async handleUpImmediately () {
      const loadingFn = state => { this.btnLoading.batchUp = state };
      const data = {
        newOffTime: this.tableInfo.list[0].expectOffTime,
        newSkuState: '1', // 1为上架，2为下架
        mdUuids: this.tableInfo.list.map(item => item.uuid)
      }
      const res = await batchUpTemporaryGoodsService(data, loadingFn);
      if (res) {
        this.$message.success('立即上架成功');
        this.goToListPage();
      }
    },
    // 图文
    handleViewPicture (row) {
      this.$router.push({
        name: 'imageTextManage',
        query: {
          skuId: row.uuid,
          skuNo: row.skuNo,
          productType: PRODUCT_TYPES_ENUMS.TEMP_PROJECT,
          fromName: this.$route.name,
          cacheKey: CacheKey
        }
      });
    },
    // 删除
    handleDelete (row) {
      this.$confirm('确定要删除吗？', '删除', {
        type: 'warning',
      }).then(() => {
        this.tableInfo.list = this.tableInfo.list.filter(item => item.frontUuid !== row.frontUuid);
      }).catch(() => {});
    },
    // 数值框change
    handleInputNumberRowChange (row, val, property) {
      const props = ['costPriceStr', 'sellPriceStr']
      if (props.includes(property)) {
        row[property] = toFixedCustomize(val);
      }
    },
    // 初始化所有数据
    initAllData () {
      this.setTableColumns();
      this.initTableData();
      this.setDatePickerOptions();
    },
    // 初始化表格数据
    initTableData () {
      const newData = this.getNewRowData();
      this.tableInfo.list = [newData];
    },
    // 设置表列
    setTableColumns (columns) {
      const defaultColumns = _.cloneDeep(this.hasNoSubmitted ? TABLE_COLUMNS : VIEW_TABLE_COLUMNS);
      const headerColumns = _.cloneDeep(columns ?? []);
      const footerColumns = _.cloneDeep(PITCURE_COL ?? []);
      this.tableInfo.columns = [...headerColumns, ...defaultColumns];
      if (!this.hasNoSubmitted) this.tableInfo.columns.push(...footerColumns)
    },
    // 获取表格新行数据
    getNewRowData (index) {
      return TABLE_COLUMNS.reduce((value, item) => {
        value[item.key] = null
        return value
      }, { frontUuid: generateUuid() + (index ?? 0) });
    },
    // 获取选择品类结果
    getSelectCategory (results) {
      this.setTableRelativeInfo({
        categoryUuid: results?.categoryUuid,
        categoryName: results?.categoryName,
        categoryNo: results?.categoryNo
      });
    },
    // 获取选择品牌结果
    getSelectBrand (results) {
      this.setTableRelativeInfo({
        // otherBrand: results.otherBrandName,
        brandName: results.brandName,
        brandUuid: results.brandUuid
      });
    },
    // 获取选择计量单位结果
    getSelectUnit (results) {
      this.setTableRelativeInfo({
        unitId: results.unitUuid,
        unitNo: results.unitNo,
        unitName: results.unitName
      });
    },
    // 设置已勾选表格相关信息
    setTableRelativeInfo (data) {
      this.tableInfo.selection.forEach(item => {
        const index = this.tableInfo.list.findIndex(cur => item.frontUuid === cur.frontUuid);
        if (index === -1) return false;
        for (const key in data) {
          this.tableInfo.list[index][key] = data[key];
        }
      });
    },
    // 设置时间选择器options
    async setDatePickerOptions () {
      const res = await getOffMaxDaysService('.project_goods_add');
      if (!res?.retData) return false;
      const maxDays = res.retData - 1;
      this.pickerOptions = {
        disabledDate: (time) => {
          const MAX_DAYS_LIMIT = maxDays * 24 * 3600 * 1000;
          const isSmaller = time.getTime() <= new Date().getTime();
          const isMoreThan = time.getTime() > new Date().getTime() + MAX_DAYS_LIMIT;
          return isSmaller || isMoreThan;
        }
      }
    },
    // 提交临时项目商品新增数据
    async submitAddInfo () {
      const loadingFn = state => { this.btnLoading.submit = state };
      const data = {
        ...this.formData,
        customerNo: this.formData.customerCode,
        dtos: this.tableInfo.list
      }
      const res = await submitTemporaryGoodsInfoService(data, loadingFn);
      if (!res) return false;
      const { errorList, submitUuids } = res.retData;
      const hasSuccessed = errorList.length === 0;
      if (hasSuccessed) {
        sessionStorage.setItem(CacheKey, JSON.stringify(submitUuids));
        this.$message.success('提交成功，请继续完善商品图文后上架');
        this.reloadPage();
      } else {
        this.setTableColumns(ERROR_COL);
        this.tableInfo.list = errorList;
        this.$message.warning('提交失败，请查看异常信息');
      }
    },
    // 回显提交后的数据
    async echoSubmittedInfo () {
      if (this.hasNoSubmitted) return false;
      const uuids = sessionStorage.getItem(CacheKey);
      const res = await querySubmittedInfoService(uuids, '.project_goods_add');
      const { retData } = res ?? {};
      if (retData) {
        this.tableInfo.list = retData;
        const {
          customerNo,
          expectOffTime,
          approvalDescription,
          operName,
          opeTime,
          operDeptName
        } = retData[0];
        this.setCustomerInfo({ ...retData[0], customerCode: customerNo });
        this.formData.expectOffTime = expectOffTime;
        this.formData.approvalDescription = approvalDescription;
        this.operInfo = { operName, opeTime, operDeptName };
      }
    },
    // 返回列表页
    goToListPage () {
      this.$router.push({ name: 'temporaryProjectGoodsList' });
    }
  }
}
</script>
